package com.zhang.apipassenger.service.impl;

import com.zhang.apipassenger.service.TokenService;
import com.zhang.internalcommon.constant.CommonStatusEnum;
import com.zhang.internalcommon.constant.TokenConstants;
import com.zhang.internalcommon.dto.ResponseResult;
import com.zhang.internalcommon.dto.TokenResult;
import com.zhang.internalcommon.utils.JwtUtils;
import com.zhang.internalcommon.utils.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

	@Autowired
	StringRedisTemplate redisTemplate;

	@Override
	public ResponseResult refreshToken(String refreshTokenSrc) {
		// 解析refresh token
		TokenResult tokenResult = JwtUtils.checkToken(refreshTokenSrc);
		if (tokenResult == null) {
			return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(), CommonStatusEnum.TOKEN_ERROR.getValue());
		}
		String phone = tokenResult.getPhone();
		String identity = tokenResult.getIdentity();

		// 读取Redis中的refresh token
		String refreshTokenKey = RedisPrefixUtils.generateTokenKey(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);
		String refreshTokenRedis = redisTemplate.opsForValue().get(refreshTokenKey);
		// 	校验refresh token
		if ((StringUtils.isBlank(refreshTokenRedis)) || (!refreshTokenRedis.trim().equals(refreshTokenSrc.trim()))) {
			return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(), CommonStatusEnum.TOKEN_ERROR.getValue());
		}
		// 	生成token
		String refreshToken = JwtUtils.generateToken(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);
		String accessToken = JwtUtils.generateToken(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);

		String accessTokenKey = RedisPrefixUtils.generateTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);
		redisTemplate.opsForValue().set(accessTokenKey, accessToken, 15, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 16, TimeUnit.DAYS);

		return ResponseResult.success(tokenResult);

	}
}
